package org.zn.etl.datasource;

import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class DataSourceFactoryHolder implements ApplicationContextAware{
	
	private	ApplicationContext applicationContext;
	
	private  final static String  SPRINGDS="SpringDataSourceFactory";
	private  final static String  JDS="JdbcDataSourceFactory";
	private  final static String  SHARDINGDS="JdbcDataSourceFactory";

	public  DataSourceFactory getFactory(String type){
	
		String beanName="SpringDataSourceFactory";
		
		switch (type) {
		case "jdbc":
			beanName=JDS;
			break;
		case "spring":
			beanName=SPRINGDS;
			break;
		case "sharding":
			beanName=SHARDINGDS;
			break;

		default:
			break;
		}
		
		DataSourceFactory  dsf= (DataSourceFactory) applicationContext.getBean(beanName);
		return dsf;
		
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext=applicationContext;
	}
	
	public  DataSource find(String dsKey) {
		
		
		Map<String, DataSource>   cxtDs=applicationContext.getBeansOfType(DataSource.class);
		
		DataSource ds= cxtDs.get(dsKey);
		
		if(ds!=null) {
			return ds;
		}
		
		DataSourceFactory  dsf= (DataSourceFactory) applicationContext.getBean(JDS);
		ds=dsf.getDataSource(dsKey);
		
		if(ds!=null) {
			return ds;
		}
		
		
		
		return null;
		
	}
	
	
}
